import express from 'express'
import { authenticateToken } from '../middleware/auth.js'
import db from '../db/database.js'
import { USDT_PRECISION } from '../config.js'

const router = express.Router()

// 转换金额：除以 USDT_PRECISION
function normalizeAmount(amount, currency = 'USDT') {
  if (amount === null || amount === undefined) return 0
  if (typeof amount !== 'number') {
    amount = parseFloat(amount)
    if (isNaN(amount)) return 0
  }
  
  if (currency === 'USDT') {
    return amount / USDT_PRECISION
  }
  
  return amount
}

// 所有路由需要认证
router.use(authenticateToken)

// 获取交易记录
router.get('/', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { page = 1, pageSize = 10, type, currency } = req.query

    let query = 'SELECT * FROM transactions WHERE user_id = ?'
    const params = [userId]

    if (type) {
      query += ' AND type = ?'
      params.push(type)
    }

    if (currency) {
      query += ' AND currency = ?'
      params.push(currency)
    }

    query += ' ORDER BY created_at DESC LIMIT ? OFFSET ?'
    params.push(parseInt(pageSize), (parseInt(page) - 1) * parseInt(pageSize))

    const transactions = db.prepare(query).all(...params)

    // 转换所有交易的金额
    const normalizedTransactions = transactions.map(tx => ({
      ...tx,
      amount: normalizeAmount(tx.amount, tx.currency)
    }))

    // 获取总数
    let countQuery = 'SELECT COUNT(*) as total FROM transactions WHERE user_id = ?'
    const countParams = [userId]

    if (type) {
      countQuery += ' AND type = ?'
      countParams.push(type)
    }

    if (currency) {
      countQuery += ' AND currency = ?'
      countParams.push(currency)
    }

    const total = db.prepare(countQuery).get(...countParams).total

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: {
        list: normalizedTransactions,
        total,
        page: parseInt(page),
        pageSize: parseInt(pageSize)
      }
    })
  } catch (error) {
    next(error)
  }
})

// 获取交易详情
router.get('/:txId', async (req, res, next) => {
  try {
    const userId = req.user.userId
    const { txId } = req.params

    const transaction = db.prepare('SELECT * FROM transactions WHERE tx_id = ? AND user_id = ?').get(txId, userId)

    if (!transaction) {
      return res.status(404).json({
        code: 404,
        message: '交易不存在',
        success: false
      })
    }

    // 转换金额
    const normalizedTransaction = {
      ...transaction,
      amount: normalizeAmount(transaction.amount, transaction.currency)
    }

    res.json({
      code: 200,
      message: '获取成功',
      success: true,
      data: normalizedTransaction
    })
  } catch (error) {
    next(error)
  }
})

export default router

